package com.kgc.onlineLife.controller;

import com.alibaba.fastjson.JSONObject;
import com.kgc.onlineLife.bean.Customer;
import com.kgc.onlineLife.service.CategoryService;
import com.kgc.onlineLife.service.CustomerService;
import com.kgc.onlineLife.service.PageService;
import com.kgc.onlineLife.util.EncodeUtils;
import com.kgc.onlineLife.util.Page;
import com.sun.media.sound.SoftTuning;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * Created On : 2022/4/19.
 * <p>
 * Author     : nainai
 * <p>
 * Description: 用户Controller
 */
@Controller
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private PageService pageService;

    /**
     * @author : nainai
     * @date   : 2022/4/15
     * @param  : [java.util.Map<java.lang.String,java.lang.Object>]
     * @return : java.lang.String
     * @description : 访问用户列表页面请求
     */
    @RequestMapping("/customers/{pageNo}")
    public String customers(Map<String, Object> map, @PathVariable("pageNo") Integer pageNo){
        // 调用业务接口，查询分页
        Page page = pageService.queryPage("customer");
        page.setPageNo(pageNo);
        map.put("page", page);

        // 标识是否为搜索的内容分页
        map.put("searchPage", false);

        // 调用业务接口，查询所有用户详情，带分页
        map.put("customers", customerService.queryCustomers(page));

        return "/Admin/user_list";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/17
     * @param  : [java.util.Map<java.lang.String,java.lang.Object>, java.lang.String]
     * @return : java.lang.String
     * @description : 用户名搜索
     */
    @RequestMapping(value = "/searchCustomer", method = RequestMethod.GET, params = "name")
    public String searchCustomer(Map<String, Object> map, String name){
        // 为空时查全部
        if (name == null || name == "") {
            return "redirect:/customers/1";
        }
        // 调用业务接口，查询分页
        Page page = pageService.queryPageByName(name, "customer");
        map.put("page", page);

        // 搜索时不显示分页
        map.put("searchPageFlag", true);

        map.put("customers", customerService.queryCustomersByName(name));

        return "/Admin/user_list";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/15
     * @param  : []
     * @return : java.lang.String
     * @description : 删除用户
     */
    @RequestMapping(value = "/deleteCustomer/{id}")
    public String deleteCustomer(@PathVariable("id") Integer id){
        // 调用业务接口，修改用户状态
        if(customerService.changeCustomerStatus(id)){
            System.out.println("修改状态成功！");
        } else {
            System.out.println("修改状态失败！");
        }

        return "redirect:/customers/1";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/16
     * @param  : [java.util.Map<java.lang.String,java.lang.Object>, java.lang.Integer]
     * @return : java.lang.String
     * @description : 跳转至修改用户页面
     */
    @RequestMapping(value = "/toModCustomer/{id}")
    public String toModCustomer(Map<String, Object> map, @PathVariable("id") Integer id){
        // 调用业务接口，根据id查询用户详情
        map.put("customer", customerService.queryCustomerById(id));

        return "/Admin/customer_edit";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/18
     * @param  : [com.kgc.onlineLife.bean.Customer]
     * @return : java.lang.String
     * @description : 修改用户信息
     */
    @RequestMapping(value = "/ModCustomer")
    public String ModCustomer(Customer customer){
        customer.setPassword(EncodeUtils.testDigest(customer.getPassword()));
        if (customerService.modCustomerById(customer)){
            System.out.println("修改成功");
        } else {
            System.out.println("修改失败");
        }
        return "redirect:/customers/1";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/25
     * @param  : [com.kgc.onlineLife.bean.Customer]
     * @return : java.lang.String
     * @description : 跳转至修改当前登录用户信息
     */
    @RequestMapping("/toModAtCustomer")
    public String toModAtCustomer(Map<String, Object> map, HttpSession session){
        Customer customer = (Customer) session.getAttribute("cst");
        session.setAttribute("headImg", customer.getImageUrl());
        map.put("customer", customer);
        return "/Fore/forepage/changeCustomer";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/28
     * @param  : [com.kgc.onlineLife.bean.Customer, java.lang.String, java.util.Map<java.lang.String,java.lang.Object>, javax.servlet.http.HttpSession]
     * @return : java.lang.String
     * @description : 修改当前用户密码
     */
    @RequestMapping("/modAtCustomerPwd")
    public String modAtCustomerPwd( @RequestParam("newPwd") String newPwd, @RequestParam("password") String password, Map<String, Object> map, HttpSession session) {
        Customer customer = (Customer) session.getAttribute("cst");
        if (customer.getPassword().equals(EncodeUtils.testDigest(password))) {
            customer.setPassword(EncodeUtils.testDigest(newPwd));
            customerService.modCustomerById(customer);
            session.removeAttribute("cst");
            return "redirect:/fore/foreLoginUI";
        } else {
            map.put("pwdMsgFlag", true);
            map.put("newPwd", newPwd);
            return "/Fore/forepage/changeCustomerPwd";
        }
    }

    /**
     * @author : nainai
     * @date   : 2022/4/25
     * @param  : [com.kgc.onlineLife.bean.Customer, java.lang.String, javax.servlet.http.HttpSession, java.util.Map<java.lang.String,java.lang.Object>]
     * @return : java.lang.String
     * @description : 修改当前登录用户信息
     */
    @RequestMapping("/modAtCustomer")
    public String modAtCustomer(Customer customer, Map<String, Object> map, HttpSession session) {
        customer.setImageUrl((String) session.getAttribute("headImg"));
        customerService.modCustomerById(customer);
        session.setAttribute("cst", customerService.queryCustomerById(customer.getId()));
        return "redirect:/fore/foreIndex";
    }

    /**
     * @author : nainai
     * @date   : 2022/4/25
     * @param  : [java.util.Map<java.lang.String,java.lang.Object>, javax.servlet.http.HttpSession, org.springframework.web.multipart.MultipartFile, com.kgc.onlineLife.bean.Customer]
     * @return : java.lang.String
     * @description : 修改当前登录用户头像
     */
    @RequestMapping("/userHeaderImg")
    @ResponseBody
    public String userHeaderImg(HttpSession session, @RequestParam MultipartFile userHeaderImg) throws IOException {
        // 上传图片不为空
        String imageName = UUID.randomUUID().toString().substring(0, 8) + ".jpg";
        String realPath = session.getServletContext().getRealPath("Admin/images/customers");

        File file = new File(realPath, imageName);
        if(!file.exists()){
            file.mkdirs();
        }

        userHeaderImg.transferTo(file);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileName","images/customers/" + imageName);
        session.setAttribute("headImg", "images/customers/" + imageName);

        return jsonObject.toJSONString();
    }
}
